package so.sao.code.service.domain.handler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;

import so.sao.code.service.domain.entity.EnterpriseCustomField;
import so.sao.code.service.domain.entity.TagBatch;
import so.sao.code.service.domain.entity.TagBatchConfig;
import so.sao.code.service.domain.entity.TagOperationLog;
import so.sao.code.service.domain.event.TagBatchConfigCreateEvent;
import so.sao.code.service.domain.service.RangeActivativeDomainService;
import so.sao.code.service.infrastructure.SessionContext;
import so.sao.code.service.infrastructure.enums.CodeMessage;
import so.sao.code.service.infrastructure.enums.PrintFileDownloadMethod;
import so.sao.code.service.repository.EnterpriseCustomFieldDao;
import so.sao.code.service.repository.TagBatchDao;
import so.sao.code.service.repository.TagOperationLogDao;
import so.sao.data.dto.response.EnterpriseDTO;
import so.sao.data.dto.response.FactoryDTO;
import so.sao.data.dto.response.IndustrialComputerDTO;
import so.sao.data.feign.client.EnterpriseClient;
import so.sao.data.feign.client.FactoryClient;
import so.sao.data.feign.client.IndustrialComputerClient;
import so.sao.ffw.dto.message.TagBatchCreateMessage;
import so.sao.ffw.feign.client.TagBatchCreateClient;
import so.sao.sso.feign.dto.UserDTO;
import so.sao.tag.core.key.TagKey;
import so.sao.top.core.util.mapper.JsonMapper;
import so.sao.top.core.util.rest.RestException;


/**
 * Created by Administrator on 2017/9/11.
 */
@Component
public class TagBatchConfigCreateHandler {

	@Autowired
	TagKey tagKey;

	@Autowired
	TagBatchCreateClient tagBatchCreateClient;

	@Autowired
	TagBatchDao tagBatchDao;
	@Autowired
	JsonMapper jsonMapper;
	@Autowired
	SessionContext context;
	@Autowired
	TagOperationLogDao tagOperationLogDao;

	@Autowired
	EnterpriseCustomFieldDao enterpriseCustomFieldDao;

	@Autowired
	RangeActivativeDomainService rangeActivativeDomainService;

	@Autowired
	IndustrialComputerClient industrialComputerClient;

	@Autowired
	EnterpriseClient enterpriseClient;

	@Autowired
	FactoryClient factoryClient;

	@EventListener
	// @Async
	public void sendMessageToffw(TagBatchConfigCreateEvent event) {
		TagBatch tagBatch = event.getTagBatch();
		TagBatchConfig tagBatchConfig = event.getTagBatchConfig();
		TagBatchCreateMessage tagBatchCreationRequest = new TagBatchCreateMessage();
		tagBatchCreationRequest.setTagBatchId(tagBatch.getId());
		tagBatchCreationRequest.setStartNo(tagBatch.getSeqnumStart());
		tagBatchCreationRequest.setCodeCnt(tagBatch.getTagCount());
		tagBatchCreationRequest.setTagBatchType(tagBatch.getType().getValue());
		tagBatchCreationRequest.setFileName(tagBatch.createFileName()); // 云端压缩文件的名称
		tagBatchCreationRequest.setSeqnumFileName(tagBatch.getSeqnumFileName()); // 云端码序号文件的名称
		tagBatchCreationRequest.setFileType(tagBatchConfig.getFileType()); // 明文文件格式
		tagBatchCreationRequest.setDomain(tagBatchConfig.getUrlDomain());
		tagBatchCreationRequest.setSubDomain(tagBatch.getSubDomain());
		tagBatchCreationRequest.setDirection(tagBatchConfig.getDirection());
		tagBatchCreationRequest.setTagCountPerLine(tagBatchConfig.getTagCountPerLine());
		tagBatchCreationRequest.setRatio(tagBatch.getRatio());
		tagBatchCreationRequest.setDuplicate(tagBatch.getDuplicate());
		tagBatchCreationRequest
				.setFieldsConfigs(jsonMapper.fromCollectionJson(tagBatchConfig.getFieldsConfig(), String.class)); // 按标签列数补充后的字段配置
		tagBatchCreationRequest.setAesKey(tagKey.getKey(tagBatch.getSubDomain()));
		tagBatchCreationRequest.setEseId(tagBatch.getEseId()); // 企业ID
		EnterpriseDTO enterpriseInfo = enterpriseClient.findById(tagBatch.getEseId());
		tagBatchCreationRequest.setCompanyName(enterpriseInfo.getName());
		tagBatchCreationRequest.setCodeLength(tagBatch.getCodeLength());
		tagBatchCreationRequest.setZipPassword(tagBatch.getZipPassword());
		tagBatchCreationRequest.setMessageId(UUID.randomUUID().toString());
		tagBatchCreationRequest.setPlatform(event.getTagBatchConfig().isPlatform());
		Map<String, String> customFields = new HashMap<String, String>();
		List<String> res = jsonMapper.fromCollectionJson(tagBatchConfig.getFieldsConfig(), String.class);
		String[] strList=null; 
		switch (tagBatch.getType()) {
		case NORMAL:
		case ROLL:
		case WRAP:
			  strList  = res.stream().findFirst().get().split("\\|");
			break;
		case PACKAGE:
		case DUPLICATE:
			String[]  a = res.stream().findFirst().get().split("\\|");
			String[] b=res.get(1).split("\\|");
			  strList= new String[a.length+b.length];  
			   System.arraycopy(a, 0, strList, 0, a.length);  
			   System.arraycopy(b, 0, strList, a.length, b.length);  
			break;
		default:
			break;
		}
		 for (String str : strList) {
				if (str.startsWith("Classic") || str.startsWith("Common")) {
					EnterpriseCustomField enterpriseCustomField = enterpriseCustomFieldDao.findByfieldKeyAndEseId(str,
							tagBatch.getEseId());
					customFields.put(str, enterpriseCustomField.getFieldValue());
				}
			}
		tagBatchCreationRequest.setCustomFields(customFields);

		if (event.getTagBatchConfig().getEncryptionMethod()==2) {
			Optional<IndustrialComputerDTO> result = Optional
					.ofNullable(industrialComputerClient.findById(event.getTagBatchConfig().getTerminalId()));
			if (result.isPresent()) {
				if (result.get().getSecretKey() == null || result.get().getSecretKey().length() != 32) {
					throw new RestException(HttpStatus.NOT_IMPLEMENTED, CodeMessage.KeyLengthError);
				}
				tagBatchCreationRequest.setSubPackagePassword(result.get().getSecretKey());
				tagBatchCreationRequest.setSubPackageLines(result.get().getSegmentSize()); // 分包数
				tagBatchCreationRequest.setFactoryId(event.getTagBatchConfig().getPrintFactoryId());
				Optional<FactoryDTO> factoryDTO = Optional
						.ofNullable(factoryClient.findById(event.getTagBatchConfig().getPrintFactoryId()));
				if (factoryDTO.isPresent()) {
					tagBatchCreationRequest.setFactoryName(factoryDTO.get().getName());
				}
			}
		} 
			tagBatchCreationRequest.setEncryptType(event.getTagBatchConfig().getEncryptionMethod());
		 
		tagBatchCreationRequest.setCompanyId(event.getTagBatch().getEseId());
		if (event.getTagBatchConfig().isPlatformEncryption()) {
			tagBatchCreationRequest.setWhetherPlatEncrypt(2);
		}
		tagBatchCreationRequest.setTerminals(Lists.newArrayList(event.getTagBatchConfig().getTerminalId()));
		tagBatchCreateClient.tagBatchCreateMessageToQueue(tagBatchCreationRequest);
	}

	// @EventListener
	// @Async
	// (condition = "#event.tagBatchConfig.isPlatform")
	public void pushsupplyChain(TagBatchConfigCreateEvent event) {
		if (!event.getTagBatchConfig().isPlatform()) {
			rangeActivativeDomainService.supplyChainActive(event.getTagBatch());
		}
	}

	// @Async
	@EventListener
	public void handleTagBatchConfigId(TagBatchConfigCreateEvent event) {
		TagBatch tagBatch = event.getTagBatch();
		TagBatchConfig tagBatchConfig = event.getTagBatchConfig();
		// tagBatch.setDomain(tagBatchConfig.getUrlDomain());//二期转到批次创建
		tagBatch.setTagBatchConfigId(tagBatchConfig.getId()); // 保存印刷格式id
		tagBatch.setFileName(tagBatch.createFileName());
		tagBatchDao.save(tagBatch);
	}

	/**
	 *
	 * */
	@EventListener
	// @Async
	public void logAction(TagBatchConfigCreateEvent event) {
		UserDTO user = context.CURRECT_USER;
		TagBatch tagBatch = event.getTagBatch();
		String action = event.getOperation().getName();
		TagOperationLog log = new TagOperationLog(tagBatch.getId(), "管理端", action,
				tagBatch.getSeqnumStart() + "-" + tagBatch.getSeqnumEnd(), user.getUsername());
		tagOperationLogDao.save(log);
	}
}
